package ar.edu.unlu.sistemas.movirdroid.android;

import java.io.File;
import java.io.Serializable;
import java.util.Collection;
import java.util.Collections;
import java.util.Iterator;
import java.util.List;

import android.app.ProgressDialog;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.res.Configuration;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.Gravity;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.LinearLayout;
import android.widget.LinearLayout.LayoutParams;
import android.widget.RatingBar;
import android.widget.TextView;
import ar.edu.unlu.sistemas.movirdroid.business.util.Constants;
import ar.edu.unlu.sistemas.movirdroid.business.util.QueryResultComparator;
import ar.edu.unlu.sistemas.movirdroid.business.util.StringUtils;
import ar.edu.unlu.sistemas.ws.business.QueryResultVO;

public class QueryActivity extends AbsP2PActivity implements OnClickListener {
	
	private Collection<QueryResultVO> qresults;

	private Thread updateStateBarThread = new Thread() {
		
		public void run() {
			while (!isFinishing()) {
				try {
					//Se actualizan los imageButton
					mHandler.sendMessage(mHandler.obtainMessage(0));
					Thread.sleep(10000);
		        } catch (InterruptedException ie) {
		        	
		        }
				
			}
		}
	};
	
	public final Handler mHandler = new Handler() {
		//Se envían mensajes al handler que realizarán una acción
		//determinada por este método debido a que otro thread que no
		//sea el creador de la UI puede modificarla
		//Este código se ejecuta en el main thread
		public void handleMessage(Message msg) {
			super.handleMessage(msg);
			switch(msg.what) {
				case 0:
					updateImageButton();
					break;
				case 1:
					qresults = (Collection<QueryResultVO>)msg.obj;
					showQueryResults();
					break;
				default:
					break;
			}
		}
	};
	
	private ProgressDialog dialog;
	
	// For getting confirmation from the service
    private BroadcastReceiver serviceReceiver = new BroadcastReceiver() {

        @Override
        public void onReceive(Context context, Intent intent) {
        	int maxProgress = intent.getIntExtra("MAX_PROGESS", 100);
        	int currentProgress = intent.getIntExtra("CURRENT_PROGRESS", 0);
        	if (dialog == null || !dialog.isShowing()){
        		dialog = new ProgressDialog(QueryActivity.this);
        		dialog.setMax(maxProgress);
        		dialog.setProgress(currentProgress);
        		dialog.setTitle("");
        		dialog.setTitle("Proceso de indexación");
        		dialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
        		dialog.show();
        	} 
        	else if (maxProgress > currentProgress) dialog.setProgress(currentProgress);
        	else dialog.dismiss();
        }
    };
	
	/** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.query);
        Button btn = (Button)findViewById(R.id.button_query);
        btn.setOnClickListener(this);
        ImageButton ibtn = (ImageButton)findViewById(R.id.img_btn_index_sync);
        ibtn.setOnClickListener(this);
        bindService(new Intent(QueryActivity.this,AppService.class), mConnection, BIND_AUTO_CREATE);
        this.registerReceiver(serviceReceiver,new IntentFilter(Constants.INDEXING_INTENT));
       
    }

	public void onServiceConnectedWithActivity() {
    	super.onServiceConnectedWithActivity();
    	updateStateBarThread.start();
    }

	public void onClick(View v) {
    	switch (v.getId()) {
    	case R.id.button_query:
    		dialog = ProgressDialog.show(QueryActivity.this, "", "Realizando consulta, por favor espere...", false);
    		EditText edt = (EditText) this.findViewById(R.id.edit_text_query);
			String query = edt.getText().toString();
			this.appService.doQuery(query,mHandler);
    		break;
    	case R.id.img_btn_index_sync:
    		ImageButton btn = (ImageButton) this.findViewById(R.id.img_btn_index_sync);
    		btn.setEnabled(false);
    		this.appService.updateIndexAsinc();
    		break;
    	default:
    		if ((v.getId() >= 1000) && (v.getId() <= 2000)) {
    			DocumentLinearLayout dll = (DocumentLinearLayout) v;
    			File f = appService.getFile(dll.getDocumentVO());
    			if (f!=null) {
    				Intent intent = new Intent();
        			intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        			intent.setAction(android.content.Intent.ACTION_VIEW);
        			String type = StringUtils.getMIMEType(f);
        			intent.setDataAndType(Uri.fromFile(f), type);
        			startActivity(intent);
    			} 
    		}
    		break;
    	}
    }
    
    private void updateImageButton() {
    	ImageButton ibtn = (ImageButton) findViewById(R.id.img_btn_connected);
    	if (appService.getipAddress() != null) {
        	ibtn.setImageResource(R.drawable.online);
    	} else {
        	ibtn.setImageResource(R.drawable.offline);
    	}
        ibtn = (ImageButton) findViewById(R.id.img_btn_index_sync);
        
        if (!appService.isIndexUpdateLaunched()) {
        	if (appService.isIndexUpdated()) {
            	ibtn.setImageResource(R.drawable.online);
            	ibtn.setEnabled(false);
            } else {
            	ibtn.setImageResource(R.drawable.offline);
              	ibtn.setEnabled(true);
            	
            }
        }
        
    }
    
    @Override
	protected void onRestoreInstanceState(Bundle savedInstanceState) {
		super.onRestoreInstanceState(savedInstanceState);
		this.qresults = (Collection<QueryResultVO>) savedInstanceState.getSerializable("QRESULTS");
		if (this.qresults != null) this.showQueryResults();
	}

	@Override
	protected void onSaveInstanceState(Bundle outState) {
		if (this.qresults != null) outState.putSerializable("QRESULTS",(Serializable)this.qresults);
		super.onSaveInstanceState(outState);
	}

    /**
     * Realiza la query
     * @param query
     */
    private void showQueryResults() {
    	EditText edt = (EditText) this.findViewById(R.id.edit_text_query);
    	edt.setText(null);
    	QueryResultVO vo;
    	Iterator<QueryResultVO> it;
    	LinearLayout ll = (LinearLayout) this.findViewById(R.id.layout_query_docs_result);
    	ll.removeAllViews();
    	TextView tv;
    	if (this.qresults.isEmpty()) {
    		tv = new TextView(this);
    		tv.setTextSize(26);
    		tv.setText("No hay resultados");
    		ll.addView(tv);
    	} else {
	    	Collections.sort((List<QueryResultVO>)this.qresults, new QueryResultComparator());
	    	it = this.qresults.iterator();
	    	LinearLayout lldoc;
	    	LinearLayout lltxt;
	    	LinearLayout llrat;
	    	RatingBar rating;
	    	LayoutParams llp = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.FILL_PARENT,LinearLayout.LayoutParams.WRAP_CONTENT);
	    	llp.setMargins(0, 1, 0, 1);
	    	LayoutParams llp2 = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.FILL_PARENT,LinearLayout.LayoutParams.WRAP_CONTENT);
	    	int docId = 1000;
	    	while (it.hasNext()) {
	    		vo = it.next();
	
	    		lldoc = new DocumentLinearLayout(this,vo);
	    		lldoc.setId(docId++);
	    		lldoc.setLayoutParams(llp);
	    		lldoc.setBackgroundResource(R.drawable.border);
	    		lldoc.setClickable(true);
	    		lldoc.setOnClickListener(this);
	
	    		lltxt = new LinearLayout(this);
	    		lltxt.setGravity(Gravity.LEFT);
	    		tv = new TextView(this);
	    		tv.setTextSize(26);
	    		tv.setText(vo.getDocName());
	    		lltxt.addView(tv);
	    		lldoc.addView(lltxt);
	
	    		llrat = new LinearLayout(this);
	    		llrat.setLayoutParams(llp2);
	    		llrat.setVerticalGravity(Gravity.CENTER);
	    		llrat.setHorizontalGravity(Gravity.RIGHT);
	    		rating = new RatingBar(this,null,android.R.attr.ratingBarStyleSmall);
	    		rating.setRating(vo.getValue()*5);
	    		llrat.addView(rating);
	    		lldoc.addView(llrat);
	
	    		ll.addView(lldoc);
	    	}
    	}
    	if (dialog!=null) dialog.cancel();
    }
    
    /**
     * Crea el menu
     */
    public boolean onCreateOptionsMenu(Menu menu) {
        MenuInflater inflater = getMenuInflater();
        inflater.inflate(R.menu.main_menu, menu);
        return true;
    }
    
    /**
     * Maneja la selección de un item en el menú
     */
    public boolean onOptionsItemSelected(MenuItem item) {
    	switch (item.getItemId()) {
    	case R.id.menu_item_preferences:
    		startActivity(new Intent(QueryActivity.this,PreferencesActivity.class));
            return true;
        case R.id.menu_item_index:
        	startActivity(new Intent(QueryActivity.this,IndexActivity.class));
        	return true;
        case R.id.menu_item_quit:
        	//Ítem del menu SALIR, sale de la app
        	Log.i("Main Menu","Eligio Opcion SALIR");
        	this.appService.stopForeground(true);
        	this.stopService(new Intent(QueryActivity.this,AppService.class)); 
        	this.unbindService(this.mConnection);
        	this.finish();
            return true;
        }
        return false;
    }
    
    public void onBackPressed() {
    }

}
